package com.cloudspace.jindun.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cloudspace.jindun.R;
import com.cloudspace.jindun.activity.Woyao.CellActivitye;
import com.cloudspace.jindun.activity.Woyao.PassActivitye;
import com.cloudspace.jindun.activity.Woyao.SystemSettingsActivity;
import com.cloudspace.jindun.dao.LoginUser;
import com.cloudspace.jindun.model.UserInfoResult;
import com.cloudspace.jindun.net.manager.ImageManager;
import com.cloudspace.jindun.network.url.YXHttpUrl;
import com.cloudspace.jindun.ui.CircleImageView;
import com.cloudspace.jindun.user.UserSessionManager;
import com.cloudspace.jindun.utils.BitmapUtil;
import com.cloudspace.jindun.utils.FileUtil;
import com.cloudspace.jindun.utils.ObjUtil;
import com.cloudspace.jindun.utils.ToastMaker;
import com.cloudspace.jindun.window.SelectPicPopupWindow;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.FileNotFoundException;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class WdActivity extends CustomTitleBaseActivity {
    @Bind(R.id.back)
    ImageView mBack;
    @Bind(R.id.wd_image_head)
    CircleImageView mWdImageHead;
    @Bind(R.id.wd_text_name)
    TextView mWdTextName;
    @Bind(R.id.wd_text_phoneNum)
    TextView mWdTextPhoneNum;
    @Bind(R.id.wd_collect_r2)
    RelativeLayout mWdCollectR2;
    @Bind(R.id.wd_collect_r3)
    RelativeLayout mWdCollectR3;
    @Bind(R.id.wd_collect_r4)
    RelativeLayout mWdCollectR4;
    private SelectPicPopupWindow menuWindow;
    private String sign = "wd";
    private File file;
    private String userId;
    private String filename = "ico.png";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wd, false);
        ButterKnife.bind(this);
        initData();
    }

    private void initData() {
        if (UserSessionManager.getCurrentLoginUser().getUserName() != null) {
            mWdTextName.setText(UserSessionManager.getCurrentLoginUser().getUserName());
        }
        if (UserSessionManager.getCurrentLoginUser().getUserId() != null) {
            userId = UserSessionManager.getCurrentLoginUser().getUserId();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        setUserInfo();
    }

    private void setUserInfo() {
        if (ObjUtil.isEmpty(UserSessionManager.getCurrentLoginUser())){
            return;
        }

        LoginUser user = UserSessionManager.getCurrentLoginUser();
        if (mWdImageHead != null){
            ImageManager.loadCircleImage(this, mWdImageHead, user.getIconUrl());
        }

        if (mWdTextPhoneNum != null){
            mWdTextPhoneNum.setText(user.getUserPhone());
        }
    }

    private OnClickListener itemsOnClick = new OnClickListener() {

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_take_photo:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[]{Manifest.permission.CAMERA}, 2);
                        Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(intent2, 2);
                    } else {
                        Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(intent2, 2);
                    }

                    break;
                case R.id.btn_pick_photo:
                    Intent intent = new Intent();
                    //intent = new Intent(Intent.ACTION_GET_CONTENT);
                /* 开启Pictures画面Type设定为image */
                    intent.setType("image/*");
                /* 使用Intent.ACTION_GET_CONTENT这个Action */
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                /* 取得相片后返回本画面 */
                    startActivityForResult(intent, 1);
                    break;
                default:
                    break;
            }
        }

    };

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == 1) {
                Uri selectedImage = data.getData();
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(this
                            .getContentResolver().openInputStream(Uri.parse(selectedImage.toString())));
                    mWdImageHead.setImageBitmap(bitmap);

                    String fileName = FileUtil.getLocalFileImagePath() + "wd.png";
                    FileUtil.checkFile(fileName);
                    File file = new File(fileName);

                    String filePath = null;

                    if ((filePath = BitmapUtil.compressImage(this, bitmap, file, 20)) == null) {
                        ToastMaker.showToastShort(R.string.select_photo_error);
                        return;
                    }

                    requestData(YXHttpUrl.WD_GHTX_URI, userId, filePath, file);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }


            }
            //******************************************
            if (requestCode == 2) {
                String sdStatus = Environment.getExternalStorageState();
                if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
                    Log.i("TestFile",
                            "SD card is not avaiable/writeable right now.");
                    return;
                }

                //.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
                if (data.getExtras() != null) {
                    try {
                        Bundle bundle = data.getExtras();
                        Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
                        mWdImageHead.setImageBitmap(bitmap); // 将图片显示在ImageView里
                        String fileName = FileUtil.getLocalFileImagePath() + "wd.png";
                        FileUtil.checkFile(fileName);
                        File file = new File(fileName);

                        String filePath = null;

                        if ((filePath = BitmapUtil.compressImage(this, bitmap, file, 20)) == null) {
                            ToastMaker.showToastShort(R.string.select_photo_error);
                            return;
                        }

                        requestData(YXHttpUrl.WD_GHTX_URI, userId, filePath, file);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastMaker.showToastShort(R.string.not_take_picture);
                }
            }
        } else {
            ToastMaker.showToastShort(R.string.not_choose_picture);
        }

    }

    @OnClick({R.id.back, R.id.wd_image_head, R.id.wd_text_name, R.id.wd_collect_r2, R.id.wd_collect_r3, R.id.wd_collect_r4})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                Intent intentBack = new Intent();
                intentBack.setClass(this, MainActivity.class);
                startActivity(intentBack);
                finish();
                break;
            case R.id.wd_image_head://头像
                //                //实例化SelectPicPopupWindow
                menuWindow = new SelectPicPopupWindow(WdActivity.this, itemsOnClick);
                //显示窗口
                menuWindow.showAtLocation(WdActivity.this.findViewById(R.id.main), Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
                break;
            case R.id.wd_text_name://更改名字

                break;
            case R.id.wd_collect_r2://更改手机号
                Intent intentCall = new Intent();
                intentCall.setClass(this, CellActivitye.class);
                intentCall.putExtra("sign", sign);
                startActivity(intentCall);
                break;
            case R.id.wd_collect_r3://更改密码
                Intent intentPass = new Intent();
                intentPass.putExtra("sign", sign);
                intentPass.setClass(this, PassActivitye.class);
                startActivity(intentPass);
                break;
            case R.id.wd_collect_r4://系统设置
                Intent intentSys = new Intent();
                intentSys.putExtra("sign", sign);
                intentSys.setClass(this, SystemSettingsActivity.class);
                startActivity(intentSys);
                break;
        }
    }

    private void requestData(String url, String userId, String filename, File file) {
        OkHttpUtils.post()
                .addFile("files", filename, file)
                .url(url)
                .addParams("userId", userId)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastMaker.showToastShort(R.string.generic_error);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        UserInfoResult result = gson.fromJson(response, UserInfoResult.class);
                        if (result != null && result.status == 200) {
                            UserSessionManager.updateUserInfo(result.data);
                            setUserInfo();
                            ToastMaker.showToastShort(R.string.update_photo_success);
                        } else {
                            ToastMaker.showToastShort(R.string.update_photo_fail);
                        }
                    }
                });
    }
}
